package com.hanxiaozhang.checking;

/**
 * 〈一句话功能简述〉<br>
 * 〈多线程更新同一个对象〉
 *
 * @author hanxinghua
 * @create 2024/8/28
 * @since 1.0.0
 */
public class MultiThreadUpdateSameObject {


    public static void main(String[] args) {
        Person person = new Person("Alice", 25);

        Thread thread1 = new Thread(() -> {
            person.updateName("Bob");
        });

        Thread thread2 = new Thread(() -> {
            person.updateAge(30);
        });

        thread1.start();
        thread2.start();

        try {
            // 使用join方法来等待这两个线程执行完成
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public synchronized void updateName(String newName) {
        this.name = newName;
    }

    public synchronized void updateAge(int newAge) {
        this.age = newAge;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}
